package tech.summerly.weather.model

import android.arch.persistence.room.Entity
import android.arch.persistence.room.Ignore
import android.arch.persistence.room.Index
import android.arch.persistence.room.PrimaryKey
import com.google.gson.Gson

@Entity(tableName = "user_region", indices = [(Index(value = ["fullAddress"], unique = true))])
data class UserRegion(
        @PrimaryKey(autoGenerate = true)
        val id: Long,

        val fullAddress: String,

        val regionJson: String?,

        //为了实现自定义排序功能
        val next: Long,
        val previous: Long
) {

    @Ignore
    private var lazyRegion: Region? = null

    val region: Region
        get() = lazyRegion ?: gson.fromJson(regionJson, Region::class.java).also { lazyRegion = it }

    companion object {

        const val ID_NONE = -1L

        private val gson = Gson()

        fun new(region: Region): UserRegion {
            return UserRegion(id = 0,
                    fullAddress = region.fullName,
                    regionJson = Gson().toJson(region),
                    next = ID_NONE,
                    previous = ID_NONE)
        }
    }

}
